import { Component, OnInit } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { SendorderruleService } from "../sendorderrule.service";
import { StorageService } from "../../../../common/storage.service";
import { forEach } from "@angular/router/src/utils/collection";
@Component({
  selector: 'app-add-sendorderrule',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
  providers: [SendorderruleService],
})
export class AddSendorderruleComponent implements OnInit {
  sendOrderRule: any = {}; // 规则基本数据
  dataList; // 数据
  tabViewIndex: number = 0;// tab标签页
  type;
  cols; // 表格头部
  isSave: boolean = false; //是否保存操作
  selected: any[] = [];

  punishDataList: any[] = []; //处罚 数据
  punishCols; // 处罚表格头部

  intReg: any = /^[1-9][0-9]{0,4}$/;
  doubleReg: any = /^[1-9][0-9]{0,1}$|(^([1-9][0-9]{0,1})\.([0-9]{1,2})$)|^[0]\.([0-9]{1,2})$/;

  saveBtnFlag: Boolean = false; // 提交按钮是否可用
  suggestNumError;
  secondLevelPlusRateUnPayTeamError;
  secondLevelPlusRateHowMuchReceiveError;
  secondLevelPlusRateBelongToError;
  secondLevelPlusRateBackOrderError;
  secondLevelPlusRatePassRateError;
  secondLevelMinusRateComplainError;
  secondLevelMinusRateGeneralPunishNumError;
  secondLevelMinusRateGeneralPunishScoreError;
  secondLevelMinusRateServicePunishNumError;
  secondLevelMinusRateServicePunishScoreError;
  secondLevelMinusRateAccidentPunishNumError;
  secondLevelMinusRateAccidentPunishScoreError;
  firstLevelConstructionInBuidingNumNumberError;

  constructor(private router: Router, private routeInfo: ActivatedRoute, private storage: StorageService, private service: SendorderruleService) { }

  ngOnInit() {

    this.cols = [
      { field: 'sort', header: '排序', width: '100px', frozen: false, sortable: true },
      { field: 'content', header: '条件', width: '420px', frozen: false, sortable: true }
    ];
    this.punishCols = [
      { field: 'check', header: '', width: '50px', frozen: false, editable: true, tem: true, temread: true },
      { field: 'type', header: '处罚类型', width: '240px', frozen: false },
      { field: 'num', header: '达到次数X/个', width: '160px', frozen: false, editable: true, tem: true, temread: true, required: true, pattern: this.intReg },
      { field: 'score', header: '扣分Y/分', width: '160px', frozen: false, editable: true, tem: true, temread: true, required: true, pattern: this.doubleReg }
    ];

    this.routeInfo.params.subscribe((params) => {
      this.type = params.type;
      if (this.type == 'team') {
        this.tabViewIndex = 0;
      } else if (this.type == 'supervisor') {
        this.tabViewIndex = 1;
      }

      if (!this.type) this.type = "team";
      this.loadDetail(this.type);
    });

  }

  /**
   * 是否匹配正则
   * @param data
   * @param pattern
   * @returns {any}
   */
  isRegex(data, pattern) {
    if (data) {
      return pattern.test(data)
    }
    return true
  }

  /**
   * 检查表格输入框
   * @param isSelect
   * @param data
   * @param pattern
   * @returns {any}
   */
  check(isSelect, data, pattern) {
    if (!data) {
      if (isSelect) {
        return '不能为空';
      }
    } else if (!pattern.test(data)) {
      return '扣分格式错误';
    }
  }

  /**
   * 验收标准上移
   * @param index
   */
  checkStandardMoveUp(index) {
    if (index == 0) {
      // this.error('已经是第一行了！')
      return;
    }
    let doc = this.dataList.splice(index, 1);
    doc[0].sort = index + 1 - 1;
    this.dataList.splice(index - 1, 0, doc[0]);
    this.dataList[index].sort = index + 1;
    this.dataList = this.dataList.concat([])
  }

  /**
   * 验收标准下移
   * @param index
   */
  checkStandardMoveDown(index) {
    if (index == this.dataList.length - 1) {
      // this.error('已经是最后一行了！')
      return;
    }
    let doc = this.dataList.splice(index, 1);
    doc[0].sort = index + 1 + 1;
    this.dataList.splice(index + 1, 0, doc[0]);
    this.dataList[index].sort = index + 1;
    this.dataList = this.dataList.concat([])
  }

  /**
   * 页面tab切换事件
   * @param event
   */
  onTabChange(event) {
    if (this.isSave) {
      if (event.index == 0) {
        this.type = 'team';
      } else if (event.index == 1) {
        this.type = 'supervisor';
      }
      this.returnBtn();
      event.open();
    } else {
      this.leaveCheck(event);
    }
  }

  /**
   * tab页离开后的验证
   */
  leaveCheck(event) {
    this.storage.makesureService.emit({
      message: '您存在未保存的数据，是否确定离开？',
      header: '提示',
      icon: '',
      rejectVisible: true,
      acceptVisible: true,
      acceptLabel: '直接离开',
      rejectLabel: '先保存',
      reject: () => {
      },
      accept: () => {
        if (event.index == 0) {
          this.type = 'team';
        } else if (event.index == 1) {
          this.type = 'supervisor';
        }
        this.returnBtn();
        event.open();
      }
    });
  }

  /**
   * 保存数据
   */
  save() {
    // 输入框验证
    this.saveBtnFlag = false;
    this.validSuggestNum();
    this.validSecondLevelPlusRateUnPayTeam();
    this.validSecondLevelPlusRateHowMuchReceive();
    this.validSecondLevelPlusRateBelongTo();
    this.validSecondLevelPlusRateBackOrder();
    this.validSecondLevelPlusRatePassRate();
    this.validSecondLevelMinusRateComplain();
    this.validSecondLevelMinusRateGeneralPunishNum();
    this.validSecondLevelMinusRateGeneralPunishScore();
    this.validSecondLevelMinusRateServicePunishNum();
    this.validSecondLevelMinusRateServicePunishScore();
    this.validSecondLevelMinusRateAccidentPunishNum();
    this.validSecondLevelMinusRateAccidentPunishScore();
    this.validFirstLevelConstructionInBuidingNumNumber();

    if (this.saveBtnFlag) return;

    //  百分比数据验证
    let addpercent = this.sendOrderRule['secondLevelPlusRateUnPayTeam'] +
      this.sendOrderRule['secondLevelPlusRateBelongTo'] +
      this.sendOrderRule['secondLevelPlusRateBackOrder'] +
      this.sendOrderRule['secondLevelPlusRatePassRate'] +
      this.sendOrderRule['secondLevelMinusRateComplain']

    if (addpercent != 100) {
      this.storage.makesureService.emit({
        message: '加分与减分占比百分比的总和等于100%才能提交！',
        header: '提示',
        icon: '',
        acceptVisible:false,
        rejectVisible:false,
      })
      return
    }

    this.sendOrderRule['type'] = this.type;

    // 处罚数据放入属性中
    this.sendOrderRule['secondLevelMinusRateGeneralPunish'] = this.punishDataList[0].check;
    this.sendOrderRule['secondLevelMinusRateGeneralPunishNum'] = this.punishDataList[0].num;
    this.sendOrderRule['secondLevelMinusRateGeneralPunishScore'] = this.punishDataList[0].score;
    this.sendOrderRule['secondLevelMinusRateServicePunish'] = this.punishDataList[1].check;
    this.sendOrderRule['secondLevelMinusRateServicePunishNum'] = this.punishDataList[1].num;
    this.sendOrderRule['secondLevelMinusRateServicePunishScore'] = this.punishDataList[1].score;
    this.sendOrderRule['secondLevelMinusRateAccidentPunish'] = this.punishDataList[2].check;
    this.sendOrderRule['secondLevelMinusRateAccidentPunishNum'] = this.punishDataList[2].num;
    this.sendOrderRule['secondLevelMinusRateAccidentPunishScore'] = this.punishDataList[2].score;

    // 循环出表格数据放入 三级指标属性中
    this.dataList.forEach(element => {
      if (this.sendOrderRule['thirdLevelPassRateTopToBottomContent'] == element.content) {
        this.sendOrderRule['thirdLevelPassRateTopToBottomSort'] = element.sort;
      } else if (this.sendOrderRule['thirdLevelReceiveBottomToTopContent'] == element.content) {
        this.sendOrderRule['thirdLevelReceiveBottomToTopSort'] = element.sort;
      } else if (this.sendOrderRule['thirdLevelCreateTimeBottomToTopContent'] == element.content) {
        this.sendOrderRule['thirdLevelCreateTimeBottomToTopSort'] = element.sort;
      }
    }
    );
    this.storage.loading();
    // 发送保存信息
    this.service.save(this.sendOrderRule).then(data => {
      this.storage.loadout();
      if (data.result) {
        this.success('操作成功！');
        this.isSave = true;
        this.router.navigate(['/saas/engineer/constructionconfig/sendorderrule/', this.type]);
      } else {
        this.error('操作失败，请重新操作!')
      }
    }
    );

  }

  /**
   * 加载
   * @param type
   */
  loadDetail(type) {
    this.storage.loading();

    this.punishDataList = [];
    this.dataList = [];

    this.service.findDetail(type).then(data => {
      if (data.result) {
        this.sendOrderRule = data.data;
        //  三级指标列表数据
        this.dataList = [];
        this.dataList.push({ content: this.sendOrderRule['thirdLevelPassRateTopToBottomContent'], sort: this.sendOrderRule['thirdLevelPassRateTopToBottomSort'] });
        this.dataList.push({ content: this.sendOrderRule['thirdLevelReceiveBottomToTopContent'], sort: this.sendOrderRule['thirdLevelReceiveBottomToTopSort'] });
        this.dataList.push({ content: this.sendOrderRule['thirdLevelCreateTimeBottomToTopContent'], sort: this.sendOrderRule['thirdLevelCreateTimeBottomToTopSort'] });
        this.dataList.sort((o1, o2) => {
          return o1.sort - o2.sort;
        });
        // 默认值
        if (!this.sendOrderRule['secondLevelPlusRateUnPayTeam']) this.sendOrderRule['secondLevelPlusRateUnPayTeam'] = 0;
        if (!this.sendOrderRule['secondLevelPlusRateHowMuchReceive']) this.sendOrderRule['secondLevelPlusRateHowMuchReceive'] = 2;
        if (!this.sendOrderRule['secondLevelPlusRateBelongTo']) this.sendOrderRule['secondLevelPlusRateBelongTo'] = 0;
        if (!this.sendOrderRule['secondLevelPlusRateBackOrder']) this.sendOrderRule['secondLevelPlusRateBackOrder'] = 0;
        if (!this.sendOrderRule['secondLevelPlusRatePassRate']) this.sendOrderRule['secondLevelPlusRatePassRate'] = 0;
        if (!this.sendOrderRule['secondLevelMinusRateComplain']) this.sendOrderRule['secondLevelMinusRateComplain'] = 0;
        // 处罚列表数据
        this.punishDataList = [];
        this.punishDataList.push({ check: this.sendOrderRule['secondLevelMinusRateGeneralPunish'], type: "一般处罚", num: this.sendOrderRule['secondLevelMinusRateGeneralPunishNum'], score: this.sendOrderRule['secondLevelMinusRateGeneralPunishScore'] });
        this.punishDataList.push({ check: this.sendOrderRule['secondLevelMinusRateServicePunish'], type: "服务类处罚", num: this.sendOrderRule['secondLevelMinusRateServicePunishNum'], score: this.sendOrderRule['secondLevelMinusRateServicePunishScore'] });
        this.punishDataList.push({ check: this.sendOrderRule['secondLevelMinusRateAccidentPunish'], type: "安全事故处罚", num: this.sendOrderRule['secondLevelMinusRateAccidentPunishNum'], score: this.sendOrderRule['secondLevelMinusRateAccidentPunishScore'] });

      } else {
        this.sendOrderRule = {};
        this.storage.makesureService.emit({
          message: '数据加载失败,请重新加载!',
          header: '提示',
          icon: '',
          reject: () => {
            this.loadDetail(this.type);
          },
          acceptVisible: false,
          rejectLabel: '重新加载',
          rejectVisible: true
        });
      }
      this.storage.loadout();
    });
  }

  /**
   * 返回操作
   */
  returnBtn() {
    this.router.navigate(['saas/engineer/constructionconfig/sendorderrule/', this.type]);
  }

  /**
   * 成功提示
   * @param msg
   */
  success(msg) {
    this.storage.messageService.emit({ severity: 'success', detail: msg })
  }

  /**
   * 错误提示
   * @param msg
   */
  error(msg) {
    this.storage.messageService.emit({ severity: 'error', detail: msg })
  }

  /**
   * 推荐数量验证
   * @param data
   */
  validSuggestNum() {
    let suggestNum = this.sendOrderRule['suggestNum'];

    this.suggestNumError = '';
    if (suggestNum == null || suggestNum.length == 0) {
      this.saveBtnFlag = true;
      this.suggestNumError = '请输入推荐数量';
    }
  }

  /**
   * 未接单优先验证
   * @param data
   */
  validSecondLevelPlusRateUnPayTeam() {
    let secondLevelPlusRateUnPayTeam = this.sendOrderRule['secondLevelPlusRateUnPayTeam'];

    this.secondLevelPlusRateUnPayTeamError = '';
    if (secondLevelPlusRateUnPayTeam == null || secondLevelPlusRateUnPayTeam.length == 0) {
      this.secondLevelPlusRateUnPayTeamError = '请输入未接单优先';
      this.saveBtnFlag = true;
    }
  }

  /**
   * 接单最大量验证
   * @param data
   */
  validSecondLevelPlusRateHowMuchReceive() {
    let secondLevelPlusRateHowMuchReceive = this.sendOrderRule['secondLevelPlusRateHowMuchReceive'];

    this.secondLevelPlusRateHowMuchReceiveError = '';
    if (secondLevelPlusRateHowMuchReceive == null || secondLevelPlusRateHowMuchReceive.length == 0) {
      this.secondLevelPlusRateHowMuchReceiveError = '请输入接单最大量';
      this.saveBtnFlag = true;
    }
  }

  /**
   * 所属门店验证
   * @param data
   */
  validSecondLevelPlusRateBelongTo() {
    let secondLevelPlusRateBelongTo = this.sendOrderRule['secondLevelPlusRateBelongTo'];

    this.secondLevelPlusRateBelongToError = '';
    if (secondLevelPlusRateBelongTo == null || secondLevelPlusRateBelongTo.length == 0) {
      this.secondLevelPlusRateBelongToError = '请输入所属门店';
      this.saveBtnFlag = true;
    }
  }

  /**
   * 回单率验证
   * @param data
   */
  validSecondLevelPlusRateBackOrder() {
    let secondLevelPlusRateBackOrder = this.sendOrderRule['secondLevelPlusRateBackOrder'];

    this.secondLevelPlusRateBackOrderError = '';
    if (secondLevelPlusRateBackOrder == null || secondLevelPlusRateBackOrder.length == 0) {
      this.secondLevelPlusRateBackOrderError = '请输入回单率';
      this.saveBtnFlag = true;
    }
  }

  /**
   * 满意度验证
   * @param data
   */
  validSecondLevelPlusRatePassRate() {
    let secondLevelPlusRatePassRate = this.sendOrderRule['secondLevelPlusRatePassRate'];

    this.secondLevelPlusRatePassRateError = '';
    if (secondLevelPlusRatePassRate == null || secondLevelPlusRatePassRate.length == 0) {
      this.secondLevelPlusRatePassRateError = '请输入满意度';
      this.saveBtnFlag = true;
    }
  }

  /**
   * 投诉验证
   * @param data
   */
  validSecondLevelMinusRateComplain() {
    let secondLevelMinusRateComplain = this.sendOrderRule['secondLevelMinusRateComplain'];

    this.secondLevelMinusRateComplainError = '';
    if (secondLevelMinusRateComplain == null || secondLevelMinusRateComplain.length == 0) {
      this.secondLevelMinusRateComplainError = '请输入投诉';
      this.saveBtnFlag = true;
    }
  }

  /**
   * 一般惩罚达到次数x
   * @param data
   */
  validSecondLevelMinusRateGeneralPunishNum() {
    let secondLevelMinusRateGeneralPunish = this.punishDataList[0].check;
    let secondLevelMinusRateGeneralPunishNum = this.punishDataList[0].num;

    // this.secondLevelMinusRateGeneralPunishNumError = '';
    if (secondLevelMinusRateGeneralPunish && !secondLevelMinusRateGeneralPunishNum) {
      // this.secondLevelMinusRateGeneralPunishNumError = '达到次数x不能为空！';
      this.saveBtnFlag = true;
    }
    if (secondLevelMinusRateGeneralPunishNum && !this.intReg.test(secondLevelMinusRateGeneralPunishNum)) {
      this.saveBtnFlag = true;
    }
  }

  /**
   * 一般惩罚扣分y
   * @param data
   */
  validSecondLevelMinusRateGeneralPunishScore() {
    let secondLevelMinusRateGeneralPunish = this.punishDataList[0].check;
    let secondLevelMinusRateGeneralPunishScore = this.punishDataList[0].score;

    // this.secondLevelMinusRateGeneralPunishScoreError = '';
    if (secondLevelMinusRateGeneralPunish && !secondLevelMinusRateGeneralPunishScore) {
      // this.secondLevelMinusRateGeneralPunishScoreError = '扣分y不能为空！';
      this.saveBtnFlag = true;
    }
    if (secondLevelMinusRateGeneralPunishScore && !this.doubleReg.test(secondLevelMinusRateGeneralPunishScore)) {
      this.saveBtnFlag = true;
    }
  }

  /**
   * 服务类处罚达到次数x
   * @param data
   */
  validSecondLevelMinusRateServicePunishNum() {
    let secondLevelMinusRateServicePunish = this.punishDataList[1].check;
    let secondLevelMinusRateServicePunishNum = this.punishDataList[1].num;

    // this.secondLevelMinusRateServicePunishNumError = '';
    if (secondLevelMinusRateServicePunish && !secondLevelMinusRateServicePunishNum) {
      // this.secondLevelMinusRateServicePunishNumError = '达到次数x不能为空！';
      this.saveBtnFlag = true;
    }
    if (secondLevelMinusRateServicePunishNum && !this.intReg.test(secondLevelMinusRateServicePunishNum)) {
      this.saveBtnFlag = true;
    }
  }

  /**
   * 服务类处罚扣分y
   * @param data
   */
  validSecondLevelMinusRateServicePunishScore() {
    let secondLevelMinusRateServicePunish = this.punishDataList[1].check;
    let secondLevelMinusRateServicePunishScore = this.punishDataList[1].score;

    // this.secondLevelMinusRateServicePunishScoreError = '';
    if (secondLevelMinusRateServicePunish && !secondLevelMinusRateServicePunishScore) {
      // this.secondLevelMinusRateServicePunishScoreError = '扣分y不能为空！';
      this.saveBtnFlag = true;
    }
    if (secondLevelMinusRateServicePunishScore && !this.doubleReg.test(secondLevelMinusRateServicePunishScore)) {
      this.saveBtnFlag = true;
    }
  }

  /**
   * 安全事故处罚达到次数x
   * @param data
   */
  validSecondLevelMinusRateAccidentPunishNum() {
    let secondLevelMinusRateAccidentPunish = this.punishDataList[2].check;
    let secondLevelMinusRateAccidentPunishNum = this.punishDataList[2].num;

    // this.secondLevelMinusRateAccidentPunishNumError = '';
    if (secondLevelMinusRateAccidentPunish && !secondLevelMinusRateAccidentPunishNum) {
      // this.secondLevelMinusRateAccidentPunishNumError = '达到次数x不能为空！';
      this.saveBtnFlag = true;
    }
    if (secondLevelMinusRateAccidentPunishNum && !this.intReg.test(secondLevelMinusRateAccidentPunishNum)) {
      this.saveBtnFlag = true;
    }
  }

  /**
   * 安全事故处罚扣分y
   * @param data
   */
  validSecondLevelMinusRateAccidentPunishScore() {
    let secondLevelMinusRateAccidentPunish = this.punishDataList[2].check;
    let secondLevelMinusRateAccidentPunishScore = this.punishDataList[2].score;

    // this.secondLevelMinusRateAccidentPunishScoreError = '';
    if (secondLevelMinusRateAccidentPunish && !secondLevelMinusRateAccidentPunishScore) {
      // this.secondLevelMinusRateAccidentPunishScoreError = '扣分y不能为空！';
      this.saveBtnFlag = true;
    }
    if (secondLevelMinusRateAccidentPunishScore && !this.doubleReg.test(secondLevelMinusRateAccidentPunishScore)) {
      this.saveBtnFlag = true;
    }
  }


  /**
   * 在施工队最多数量
   * @param data
   */
  validFirstLevelConstructionInBuidingNumNumber() {
    let firstLevelConstructionInBuidingNum = this.sendOrderRule['firstLevelConstructionInBuidingNum'];
    let firstLevelConstructionInBuidingNumNumber = this.sendOrderRule['firstLevelConstructionInBuidingNumNumber'];

    this.firstLevelConstructionInBuidingNumNumberError = '';
    if (firstLevelConstructionInBuidingNum && !firstLevelConstructionInBuidingNumNumber) {
      this.firstLevelConstructionInBuidingNumNumberError = '请输入在施工地数量';
      this.saveBtnFlag = true;
    }
  }

}
